<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1,minimum-scale=1,user-scalable=no">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<script src="js/jquery.js"></script>
	<script src="js/turntable.js"></script>
    <script src="/resources/util.js"></script>
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
	<title>幸运大转盘</title>
	<style>
		body{
			background: url(images/zhuanpan.jpg);
			background-position: top center;
			display: flex;
			align-items:center;
			justify-content: center;
			flex-direction: column;
			position: absolute;
			height: 100%;
            margin: 0px;
            padding: 0px;
		}
		.lottery {
			position: relative;
			display: inline-block;
			border: none;
		}

		#start {
			width: 24%;
			height:25%;
			position: absolute;
			cursor: pointer;
			left:38%;
			top:34%;
		}

		#myCanvas {
			width: 100%;
			margin: auto;
		}
        .rates{
            position: relative;
            display: flex;
			width: 100%;
			font-size: 14px;
            margin-bottom: 20px;
        }
        .share_mode{
            position: absolute;
            width: 100%;
            height: 100%;
            background-color: green;
            color: #fff;
            align-items:center;
            justify-content: center;
            display: none;
            background-image: url();
            background-repeat: no-repeat;
            background-position: center right;
            z-index: 1;
        }
		.rate{
			background-color: rgba(255,255,255,0.75);
			color: #000;
			font-weight: bold;
			border-radius: 3px;
			height: 30px;
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 1px;
		}
		.rate.selected{
			background-color: red;
			color: #fff;
		}
		#reroll {
			position: absolute;
            bottom: 50px;
            right: 50px;
            border-radius: 50%;
            background-color: rgba(0,0,0,0.75);
            color: #fff;
            width: 50px;
            height: 50px;
            font-size: 12px;
            display: flex;
            justify-content: center;
            align-items: center;
		}
		.message {
			position: fixed;
			width:100%;
			width: 300px;
			height: 200px;
			top:20%;
			left: 50%;
			margin-left: -150px;
			margin-top:-50px; 
			z-index: 999;
			box-shadow: 0px 0px 15px #000;
			color: #fff;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			font-size: 14px;
			display: none;
		}
		.message p {padding-left:2em;padding-right:2em;}
		.message>svg{
			pointer-events: none; display: block; width: 35px; height: 35px;fill: #fff;
		}
		.message.success{
			background-color: rgba(38,146,0,0.95);
            height: 480px;
		}
		.message.fail{
			background-color: rgba(0,102,153,0.95);
            height: 450px;
		}
        .failMessage{
            font-size: 12px;
            line-height: 20px;
            
        }
        .failMessage p{
            margin: 5px 0px;
        }
        .failMessage .detail{
            overflow: auto;
            height: 100px;
            border: #fff solid 1px;
            padding: 0px;
            margin: 0px 2em;
            border-width: 1px 0px;
        }
        .failMessage .detail>span{
            display: block;
        }
		.message .action{
			display: flex;
			width: 100%;
			justify-content: center;
		}
		.message .action a{
			border: #fff solid 1px;
			border-radius: 5px;
			color: #fff;
			text-decoration:none;
			text-align: center;
			padding: 5px;
			width: 100px;
			font-size: 13px;
            margin: 5px;
		}
		.cancel{
			position: absolute;
			top: 10px;
			right: 10px;
		}
		.cancel svg{
			width:15px;
			height: 15px;
			pointer-events: none;
			display: block;
			fill:#fff;
		}
		#product{font-weight:700;}
        .paymentAction{
            display: none;
            color: #fff;
            font-size: 12px;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            padding: 10px;
        }
        .paymentAction span{
            display: flex;
            align-items: center;
            justify-content: center;
            padding:10px;
        }
        .paymentAction span>a{
            border: #fff solid 1px;
			border-radius: 5px;
			color: #fff;
			text-decoration:none;
			text-align: center;
			padding: 5px;
			width: 100px;
			font-size: 13px;
            margin: 5px;
        }
        .qrcode{
            position:fixed;
            right: 10px;
            top: 10px;
            background-color:#fff;
            width: 30px;
            height: 30px;
            padding: 5px;
        }
        .qrcode svg{
            fill:#000;
        }
        .loading{
            z-index: 9999;
            display: none;
            position: fixed;
            left:0px;
            top:0px;
            width: 100%;
            height: 100%;
            padding:0px;
            background-color: rgba(0,0,0,0.75);
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }
        .loading .timeout{
            display: none;
            text-align: center;
            font-size: 12px;
            color: #fff;
        }
        .loading .error{
            display: none;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        .loading .error .errorMessage{
            color: #fff;
            font-size: 12px;
            width: 250px;
            overflow: hidden;
            box-sizing: border-box;
        }
        .loading .error .close{
            border: #fff solid 1px;
            border-radius: 5px;
            color: #fff;
            text-decoration:none;
            text-align: center;
            padding: 5px;
            width: 100px;
            font-size: 13px;
            margin: 5px;
        }
        /*Loading动画*/
        @-webkit-keyframes line-scale-pulse-out-rapid {
          0% {
            -webkit-transform: scaley(1);
                    transform: scaley(1); }

          80% {
            -webkit-transform: scaley(0.3);
                    transform: scaley(0.3); }

          90% {
            -webkit-transform: scaley(1);
                    transform: scaley(1); } }

        @keyframes line-scale-pulse-out-rapid {
          0% {
            -webkit-transform: scaley(1);
                    transform: scaley(1); }

          80% {
            -webkit-transform: scaley(0.3);
                    transform: scaley(0.3); }

          90% {
            -webkit-transform: scaley(1);
                    transform: scaley(1); } }

        .line-scale-pulse-out-rapid > div {
          background-color: #fff;
          width: 4px;
          height: 35px;
          border-radius: 2px;
          margin: 2px;
          -webkit-animation-fill-mode: both;
                  animation-fill-mode: both;
          display: inline-block;
          -webkit-animation: line-scale-pulse-out-rapid 0.9s 0s infinite cubic-bezier(.11, .49, .38, .78);
                  animation: line-scale-pulse-out-rapid 0.9s 0s infinite cubic-bezier(.11, .49, .38, .78); }
          .line-scale-pulse-out-rapid > div:nth-child(2), .line-scale-pulse-out-rapid > div:nth-child(4) {
            -webkit-animation-delay: 0.25s !important;
                    animation-delay: 0.25s !important; }
          .line-scale-pulse-out-rapid > div:nth-child(1), .line-scale-pulse-out-rapid > div:nth-child(5) {
            -webkit-animation-delay: 0.5s !important;
                    animation-delay: 0.5s !important; }
        
        .share{
            width: 100%;
            left: 0px;
            top:0px;
            background: rgba(0,0,0,0.5);
            color: #fff;
            font-size: 12px;
            display: none;
            position: relative
        }
        .share_history{
            position: absolute;
            height: 100px;
            width: 100%;
            background-color: #000;
            left: 0px;
            top: -101px;
            background-color: rgba(0,0,0,0.5);
            overflow: auto;
            font-size: 12px;
            display: none;
        }
        .share_history p{
            display: flex;
            justify-content: space-between;
            padding: 5px;
            margin: 0px;
        }
        .share>div:first-of-type{
            display: flex;
            justify-content: space-between;
            width: 100%;
            padding: 5px;
            box-sizing: border-box;
            background-image: url();
            background-size: 16px;
            background-repeat: no-repeat;
            background-position: 2px center;
            padding-left: 20px;
        }
        .share_rate_mul{
            position: relative;
            height:3px;
            background-color: rgba(0,255,0,0.75);
            max-width: 100%;
        }
        .share_rate_mul>span{
            position: absolute;
            bottom:-15px;
            background-color: rgba(0,255,0,0.75);
            color: #fff;
            height: 15px;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0px 5px;
            box-sizing: border-box;
            right: 0px;
        }
        .share_tip{
            position: fixed;
            right: 80px;
            top: 10px;
            width: 250px;
            height: 120px;
            border-width: 0;
            border-style: solid;
            border-color: transparent;
            border-bottom-width: 10px;
            color: rgba(0,0,0,0.5);
            border-radius: 10px;
            display: none;
            justify-content: center;
            align-items: center;
            background-color: rgba(0, 0, 0,0.75);
            padding-top: 10px;
            z-index: 1;
        }
        .share_tip>i{
            width: 16px;
            height: 10px;
            color: rgba(0, 0,0, 0.75);
            border-width: 0px 0px 10px;
            border-style: solid;
            left: 100%;
            top: 0px;
            border-radius: 0px 0px 20px;
            position: absolute;
        }
        .share_tip .talk{
            color: #fff;
        }
        .share_tip .talk p{
            padding: 0px;
            margin: 0px;
            font-size: 13px;
            line-height: 20px;
        }
        .share_tip .talk p.share_tip_close{
            text-align: center;
            width:60px;
            margin: auto;
            padding: 5px;
            border:#fff solid 1px;
            margin-top: 10px;
            border-radius: 5px;
        }
        .contacts{
            display: none;
            position: fixed;
            height: 100%;
            width: 100%;
            z-index: 998;
            background-color: rgba(0,0,0,0.5);
            left: 0px;
            top: 0px;
        }
        .contacts>div{
            position: fixed;
            display:flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            width: 300px;
            height: 300px;
            background-color: #fff;
            left: 50%;
            top:50%;
            margin-left: -150px;
            margin-top: -150px;
        }
        #ladingCode img{
            width: 150px;
            height: 150px;
        }
        .shop_home,.shop_record,.service{
            position: fixed;
            top: 10px;
            left: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            font-size: 12px;
            color: #fff;
        }
        .shop_record{
            left: 70px;
        }
        .service{
            left: 130px;
            display: none;
        }
        .service span:first-of-type{
            width: 50px;
            height: 50px;
            background-color: rgba(0,0,0,0.75);
            border-radius: 50%;
            padding: 10px;
            box-sizing: border-box;
        }
        .service span svg{
            fill:#fff;
        }
        .service_detail{
            position: relative;
            display: none;
            position: fixed;
            padding: 30px;
            background: #003366;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            z-index: 1;
            color: #fff;
            font-size: 12px;
        }
        .service_detail p{
            text-align: center;
            font-size: 16px;
            background: #fff;
            padding: 5px;
            margin: 0px;
            border-radius: 5px;
            color: #000;
        }
        .service_detail a{
            position: absolute;
            width: 16px;
            height: 16px;
            top: 10px;
            right: 10px;
            color: #fff;
        }
        .service_detail a svg{
            fill:#fff;
        }
        .service_detail span{
            margin-bottom: 10px;
            line-height: 22px;
        }
        .shop_home>span:first-of-type,.shop_record>span:first-of-type{
            padding: 10px;
            display: block;
            background-color: rgba(0,0,0,0.75);
            border-radius: 50%;
        }
        .shop_home img,.shop_record img{
            width: 30px;
            height: 30px;
            display: block;
        }
        .broadcast{
            position: fixed;
            top:70px;
            background-color: rgba(0,255,0,0.75);
            color: #fff;
            padding: 3px;
            box-sizing: border-box;
            white-space: nowrap;
            display: none;
            font-size: 12px;
        }
        .rate{
            position: relative;
        }
        .rate span{
            position: absolute;
            display: none;
            bottom: -20px;
            height: 20px;
            background-color: rgba(0,255,0,0.75);
            color: #fff;
            font-size: 10px;
            white-space: nowrap;
            align-items: center;
            justify-content: center;
            padding: 0px 3px;
        }
        .rate.selected span{
            display: flex;
        }
        .rate.selected span:after {
            content: "";
            font-size: 0;
            line-height: 0;
            border-width: 5px;
            border-color: rgba(0,255,0,0.75);
            border-top-width: 0;
            border-style: dashed;
            border-bottom-style: solid;
            border-left-color: transparent;
            border-right-color: transparent;
            position: absolute;
            top: -5px;
            left:50%;
            margin-left: -5px;
        }
        .score_product{
            background-color: cadetblue;
            height: 430px;
            text-align: center;
            margin-top: -215px;
            top: 50%;
        }
        .my-score{
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 3px;
            color: #fff;
            font-size: 12px;
            background-color: rgba(0,255,0,0.75);
            border-radius: 5px;
            width: 150px;
            margin-top: 5px;
            
        }
        .my-score:after{
            content: "";
            position: absolute;
            right: 10px;
            width:14px;
            height:14px;
            background-image: url();
            background-repeat: no-repeat;
            background-position:center;
            background-size: 14px;
            
        }
        .my-score.update{
            background-color: #ccc;
        }
        .my-score.update:after{
            animation:loading 2s infinite linear;
            -moz-animation:loading 2s infinite linear; /* Firefox */
            -webkit-animation:loading 2s infinite linearinfinite linear; /* Safari and Chrome */
            -o-animation:loading 2s infinite linear; /* Opera */
        }

        @keyframes loading
        {
        from {transform: rotate(0deg)}
        to {transform: rotate(360deg)}
        }

        @-moz-keyframes loading/* Firefox */
        {
        from {transform: rotate(0deg)}
        to {transform: rotate(360deg)}
        }

        @-webkit-keyframes loading/* Safari and Chrome */
        {
        from {transform: rotate(0deg)}
        to {transform: rotate(360deg)}
        }

        @-o-keyframes loading/* Opera */
        {
        from {transform: rotate(0deg)}
        to {transform: rotate(360deg)}
        }
        .Agreement{
            font-size: 11px;
            color: #fff;
            line-height: 25px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .Agreement a{
            color: #fff;
        }
        .footer{
            position: absolute;
            bottom: 0px;
            left: 0px;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .pageMask{
            position: fixed;
            z-index: 9999;
            background-color:transparent;
            width: 100%;
            height: 100%;
            left: 0px;
            top: 0px;
            display: none;
        }
	</style>
    <script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
    <script type="text/javascript" src="/resources/wxapi.js"></script>
</head>

<body>
    <div class="pageMask"></div>
    <div class="shop_home">
        <span><img src=""/></span>
        <span>前往商城</span>
    </div>
    <div class="shop_record">
        <span><img src=""/></span>
        <span>中奖纪录</span>
    </div>
    <div class="service">
        <span><svg viewBox="0 0 24 24" preserveAspectRatio="xMidYMid meet" class="style-scope iron-icon" style="pointer-events: none; display: block; width: 100%; height: 100%;"><g class="style-scope iron-icon"><circle cx="9" cy="9" r="4" class="style-scope iron-icon"></circle><path d="M9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm7.76-9.64l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27zM20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z" class="style-scope iron-icon"></path></g></svg></span>
        <span>兑奖客服</span>
    </div>
    <div class="service_detail">
    </div>
    <div class="qrcode">
    <svg viewBox="0 0 64 64" preserveAspectRatio="xMidYMid meet" class="style-scope iron-icon" style="pointer-events: none; display: block; width: 100%; height: 100%;"><g class="style-scope iron-icon"><path d="M24 0h-24v24h24v-24zM20 20h-16v-16h16v16z" class="style-scope iron-icon"></path><path d="M8 8h8v8h-8v-8z" class="style-scope iron-icon"></path><path d="M0 64h24v-24h-24v24zM4 44h16v16h-16v-16z" class="style-scope iron-icon"></path><path d="M8 48h8v8h-8v-8z" class="style-scope iron-icon"></path><path d="M40 0v24h24v-24h-24zM60 20h-16v-16h16v16z" class="style-scope iron-icon"></path><path d="M48 8h8v8h-8v-8z" class="style-scope iron-icon"></path><path d="M8 28h-8v8h12v-4h-4z" class="style-scope iron-icon"></path><path d="M28 36h8v8h-8v-8z" class="style-scope iron-icon"></path><path d="M12 28h8v4h-8v-4z" class="style-scope iron-icon"></path><path d="M36 48h-8v4h4v4h4v-4z" class="style-scope iron-icon"></path><path d="M24 28v4h-4v4h8v-8z" class="style-scope iron-icon"></path><path d="M32 16h4v8h-4v-8z" class="style-scope iron-icon"></path><path d="M36 32v4h8v-8h-12v4z" class="style-scope iron-icon"></path><path d="M28 24h4v4h-4v-4z" class="style-scope iron-icon"></path><path d="M36 56h8v8h-8v-8z" class="style-scope iron-icon"></path><path d="M28 56h4v8h-4v-8z" class="style-scope iron-icon"></path><path d="M36 44h4v4h-4v-4z" class="style-scope iron-icon"></path><path d="M36 12v-8h-4v-4h-4v16h4v-4z" class="style-scope iron-icon"></path><path d="M48 56h4v8h-4v-8z" class="style-scope iron-icon"></path><path d="M48 48h8v4h-8v-4z" class="style-scope iron-icon"></path><path d="M44 52h4v4h-4v-4z" class="style-scope iron-icon"></path><path d="M40 48h4v4h-4v-4z" class="style-scope iron-icon"></path><path d="M56 40v4h4v4h4v-8h-4z" class="style-scope iron-icon"></path><path d="M60 52h-4v12h8v-8h-4z" class="style-scope iron-icon"></path><path d="M40 40v4h12v-8h-8v4z" class="style-scope iron-icon"></path><path d="M48 28v4h8v4h8v-8h-8z" class="style-scope iron-icon"></path></g></svg>
    </div>
    <div class="loading" id="loading">
        <div class="line-scale-pulse-out-rapid">
          <div></div>
          <div></div>
          <div></div>
          <div></div>
          <div></div>
        </div>
        <p class="timeout">
            网络不给力，请耐心等待...
        </p>
        <p class="paymentAction">
            <span>非常抱歉，由于长时间未收到微信服务器的付款通知、或者网络/系统故障，无法显示此次抽奖结果。<br/>如果您已中奖，则会在您的“中奖纪录中”生成您的中奖商品信息，否则即表示您本次抽奖并未中奖。</span>
            <span><a class="cancelWait">关闭</a>
            <a class="restartCheck">重新检查</a>
            <a class="continueToWait">查看中奖纪录</a></span>
        </p>
        <div class="error">
            <p class="errorMessage"></p>
            <a class="close">确定</a>
        </div>
    </div>
    <div class="contacts">
        <div>
            <h3>首次使用，请提供提货信息</h3>
            <p>联系人：<input id="contacts" type="text" value=""/></p>
            <p>手机号：<input id="telephone" type="number" value=""/></p>
            <p><button id="contactsBtn">确定</button></p>
        </div>
    </div>
	<div class="message success">
		<svg viewBox="0 0 16 16" preserveAspectRatio="xMidYMid meet" focusable="false"><g><path d="M8 1c3.9 0 7 3.1 7 7s-3.1 7-7 7-7-3.1-7-7 3.1-7 7-7zM8 0c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8v0z"></path><path d="M8 13.2c-2 0-3.8-1.2-4.6-3.1l0.9-0.4c0.6 1.5 2.1 2.4 3.7 2.4s3.1-1 3.7-2.4l0.9 0.4c-0.8 2-2.6 3.1-4.6 3.1z"></path><path d="M7 6c0 0.552-0.448 1-1 1s-1-0.448-1-1c0-0.552 0.448-1 1-1s1 0.448 1 1z"></path><path d="M11 6c0 0.552-0.448 1-1 1s-1-0.448-1-1c0-0.552 0.448-1 1-1s1 0.448 1 1z"></path></g></svg>
		<p>运气真好，恭喜中奖！<br/>您免费获得商品<span id="product"></span>。</p>
        <div id="ladingCode"></div>
        <p id="ladingCodeMessage"></p>
		<div class="action"><a href="javascript:void(0)" id="success_ok">确认</a></div>
	</div>
    <div class="message score_product">
		<p>您的积分不足，购买推荐商品，立即获得高额积分！</p>
        <p class="score_product_pic"></p>
        <p class="score_product_title"></p>
        <p class="score_product_money"></p>
        <p class="score_product_amount"></p>
        <p class="score_product_give"></p>
		<div class="action"><a href="javascript:void(0)" id="score_product_cancel">关闭</a><a href="javascript:void(0)" id="score_product_ok">确认</a></div>
	</div>
	<div class="message fail">
		<svg viewBox="0 0 16 16" preserveAspectRatio="xMidYMid meet" focusable="false"><g><path d="M8 1c3.9 0 7 3.1 7 7s-3.1 7-7 7-7-3.1-7-7 3.1-7 7-7zM8 0c-4.4 0-8 3.6-8 8s3.6 8 8 8 8-3.6 8-8-3.6-8-8-8v0z"></path><path d="M7 6c0 0.552-0.448 1-1 1s-1-0.448-1-1c0-0.552 0.448-1 1-1s1 0.448 1 1z"></path><path d="M11 6c0 0.552-0.448 1-1 1s-1-0.448-1-1c0-0.552 0.448-1 1-1s1 0.448 1 1z"></path><path d="M4 10h8v1h-8v-1z"></path></g></svg>
		<p>太遗憾了，请再接再厉！</p>
        <div class="failMessage"></div>
		<a href="javascript:void(0)" class="cancel" id="cancel"><svg viewBox="0 0 16 16" preserveAspectRatio="xMidYMid meet" focusable="false"><g><path d="M16 0l-1 0.010-7 6.99-7-6.99-1-0.010v1l7 7-7 7v1h1l7-7 7 7h1v-1l-7-7 7-7v-1z"></path></g></svg></a>
		<div class="action"><a href="javascript:void(0)" id="restart">再来一次</a></div>
	</div>
	<img src="images/sorry.png" id="sorry-img" style="display:none;" />
	<div class="lottery">
		<canvas id="myCanvas" width="600" height="600">
			当前浏览器版本过低，请使用其他浏览器尝试
		</canvas>
		<img src="./images/start.png" id="start">
        <div id="reroll">换一批</div>
		<p id="message"></p>
	</div>
    <div class="footer">
        <div class="share">
            <div>
                <div class="share_history"></div>
                <div class="share_message">分享<span class="share_amount_point">0</span>人免费抽奖，更多人助力可提升中奖概率</div>
                <div>
                    <span class="share_answer_count">0人响应</span>

                </div>
            </div>
            <div class="share_rate_mul" style="width:0%">
                <span class="share_rate_mul_show"></span>
            </div>
        </div>
        <div class="share_tip"><i></i><div class="talk">
            <p>如何分享给朋友？</p>    
            <p>1，打开右上角菜单转发到群<br/>2，点击图标生成海报分享到朋友圈</p>
            <p class="share_tip_close">我知道了</p>
        </div></div>
        <div class="rates">
            <div class="share_mode">免费抽奖</div>
        </div>
        <div class="my-score"></div>
        <div class="Agreement"><input checked id="Agreement" type="checkbox"/>我同意《<a href="幸运抽奖活动使用协议.docx">幸运抽奖活动使用协议</a>》，知其规则绝对公平公正</div>
    </div>
	<script type="text/javascript">
        var token = null;
        //防止token变更
        document.cookie.split(" ").join("").split(";").forEach(function(cookie){
            if(cookie.indexOf("token")==0){
                let hostname = window.location.hostname.substring(window.location.hostname.indexOf("."));
                token = cookie.split("=")[1];
                let fn = function(){
                    document.cookie = "token="+ escape (token) + ";domain="+hostname+";path=/";
                };
                document.addEventListener("mousedown",fn);
                document.addEventListener("touchstart",fn);
                document.addEventListener("click",fn);
            }
        });
		var apiHost = "https://"+window.location.hostname+"/plugin/api";
		function GetQueryString(name) {
			 var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
			 var r = window.location.search.substr(1).match(reg);
			 if(r!=null)return  unescape(r[2]); return null;
		}
        let loading_timeout = 0;
        function showLoading(showTimeout){
            $(".line-scale-pulse-out-rapid").show();
            $("#loading").css("display","flex");
            $("#loading .timeout").hide();
            if(showTimeout){
                loading_timeout = setTimeout(function(){
                    $(".line-scale-pulse-out-rapid").hide();
                    $("#loading .timeout").show();
                },showTimeout);
            }
        }
        function hideLoading(message){
            if(message){
                $(".line-scale-pulse-out-rapid").hide();
                $("#loading .errorMessage").html("我们收到了一个错误，请截图告知管理员："+message);
                $("#loading .error").css("display","flex");
            }else{
                $("#loading").css("display","none");
            }

            window.clearTimeout(loading_timeout);
        }
        $("#loading .error .close").click(function(){
            $("#loading .errorMessage").html("");
            $("#loading .error").css("display","none");
            hideLoading();
        });
        //如果URL中有message字段，则弹出消息框
        if(GetQueryString("message")){
           alert(unescape(GetQueryString("message")));
        }
        showLoading();
        //获取当前用户账号 start
        var account = null;
        function updateAccount(){
            $.ajax({
                async: false,
                type: "GET",
                dataType: "json",
                url:apiHost + "/account.get.current",
                success:function(res){
                    account = res.result;
                },
                error:function(){
                    alert("读取用户信息失败");
                },
                complete:function(){
                    setTimeout(function(){
                        $(".my-score").removeClass("update");
                    },2000);
                }
            });
        }
        updateAccount();
        //获取当前用户账号 end
		var NUM = 4;	//随机商品个数，另外再加一个未中奖选项
		var appId = GetQueryString("app_id");
        var app_id = appId;
		var productList = [];	//保存所有商品
		var currentList = [];	//当前商品
		var selectedList = [];	//已经选择过的商品
		var leftList = [];		//剩余未选择过的商品
		var list = [];	//转盘数据
		var x = 1;	//倍数
		var rate = 0;	//中奖概率
		var throttle = false;	//是否正在抽奖中
		var ispaying = false;	//正在支付
		var wheelSurf;	//转盘
		var winData;	//中奖信息
        var luckyResult;
        var share_mode=false;//分享抽奖模式
        var share_x=0;//分享附加倍率
        var contacts = null;
        var telephone = null;
        var setting = null;//游戏设置
        //获取收货人姓名手机号
        $.ajax({
            async: false,
            type: "GET",
            dataType: "json",
            url:apiHost + "/cache.app.get?app_id="+app_id+"&key=zhuanpan.contacts."+account.id,
            success:function(res){
                if(res){
                    contacts = res.contacts;
                    telephone = res.telephone;
                }else{
                    window.location.href = "contacts.html?app_id="+app_id+"&back="+encodeURIComponent(window.location.href);
                }
            },
            error:function(){
                alert("读取用户信息失败");
            }
        });
		//productList = selectedList + leftList; selectedList包含currentList
		$.ajaxSetup({crossDomain: true, xhrFields: {withCredentials: true},contentType:"application/json;charset=utf-8"});
        //读取游戏配置
        
        $.ajax({
            async: false,
            type: "GET",
            dataType: "json",
            url:apiHost + "/cache.app.get?app_id=" + app_id + "&key=plugin.zhuanpan.setting",
            success:function(res){
                setting = res;
                if((!res.multiples)||res.multiples.length==0){
                    res.multiples = ["1","3","5"];
                    res.pay_money = 100;
                }
                if(res.random_rate_enabled){
                    res.pay_money = parseInt(res.pay_money+(res.pay_money*Math.random()*2));
                }
                res.multiples.forEach(function(m,index){
                    let item = $("<div class=\"rate\" x=\""+(m)+"\">"+m+"倍<span>"+(m*res.pay_money)+"积分</span></div>");
                    if(index==0){
                       item.addClass("selected");
                    }
                    $(".rates").append(item);
                });
//                x = Number(res.multiples[0]*res.pay_money/100);
                x = Number(res.multiples[0]);
                initSurf();
            },
            error:function(){
                alert("读取活动配置异常");
            }
        });
        //显示客服图标
        if(setting&&setting.service_weixin_enabled){
            if(setting.service_weixin_name){
                let span = $("<p/>").addClass("service_weixin_name").html(setting.service_weixin_name).click(function(){
                    var success = true;
                    var text=this;
                    if (document.body.createTextRange) {
                        var range = document.body.createTextRange();
                        range.moveToElementText(text);
                        range.select();
                    } else if (window.getSelection) {
                        var selection = window.getSelection();
                        var range = document.createRange();
                        range.selectNodeContents(text);
                        selection.removeAllRanges();
                        selection.addRange(range);
                    } else {
                        success =false;
                    }
                    if(success){
                        document.execCommand("Copy");
                        alert("客服微信号已复制，请通过微信添加好友");
                    }else{
                        alert("请手动复制微信号");
                    }
                });
                $(".service_detail").append(span);
                $(".service_detail").append($("<span>点击复制客服微信号</span>"));
            }
            if(setting.service_weixin_qrcode){
                let imgSrc = setting.service_weixin_qrcode;
                let img = $("<img/>").prop("src",imgSrc+"?imageView2/2/w/250").click(function(){
                    showLoading();
                    $.ajax({
                        url:apiHost+"/wx.app.call?name=previewImage&asyn=true",
                        type:"POST",
                        data:JSON.stringify({current:imgSrc,urls:[imgSrc]})
                    }).always(function(){
                        hideLoading();
                    });
                });
                $(".service_detail").append(img);
                $(".service_detail").append($("<span>扫码加客服为好友</span>"));
                $(".service_detail").append($("<a><svg viewBox=\"0 0 16 16\" preserveAspectRatio=\"xMidYMid meet\" focusable=\"false\"><g><path d=\"M16 0l-1 0.010-7 6.99-7-6.99-1-0.010v1l7 7-7 7v1h1l7-7 7 7h1v-1l-7-7 7-7v-1z\"></path></g></svg></a>").click(function(){
                    $(".service_detail").css("display","none");
                }));
            }
            $(".service").css("display","flex").click(function(){
                $(".service_detail").css("display","flex");
            });
        }
		//获取所有商品，并显示转盘
		function init() {
			$.get(apiHost+"/plugin.product.list?app_id="+appId+"&plugin_id=zhuanpan",null,function(res){
				let items = res.result;
				items.forEach(function(item){
//					if(item.salemoney<300) {	//只取低于300元的商品
						productList.push({"id" : item.id, "name" : item.name, "image" : item.album[0]+"?imageView2/5/w/60/h/60", "money" : item.salemoney});
//					}
				});
				initList();
                hideLoading();
			}).error(function(err){
                hideLoading(JSON.parse(err.responseText).message);
            });
		}
		//获取随机商品
		//换一批，剩余商品中随机获取，如果剩余商品数量不足，则从前面随机过的商品获取
		function initList() {
			if(productList.length <=0 ) return;
			if(leftList.length <=0 ) leftList = productList.slice(0);	//初始化未选择过的商品
			currentList = [];
			var ran,item,money;
			if(productList.length <= NUM) {	//商品数量不足，则全部上架
				selectedList = [];
				Array.prototype.push.apply(currentList, leftList);
				Array.prototype.push.apply(selectedList, leftList);
				leftList = [];
			}
			else {
				for(var i=0;i<NUM;i++) {
					if(leftList.length<=0)  {	//如果剩余商品数量不足，则从前面随机过的商品补充
						Array.prototype.push.apply(leftList, selectedList);
						selectedList = [];
					}
					ran = Math.floor(Math.random() * leftList.length);
					item = leftList[ran];
					leftList.splice(ran, 1);
					currentList.push(item);
				}
				Array.prototype.push.apply(selectedList, currentList);
			}
			//将随机商品列表转换为转盘数据
			list = [];
			for(var i=0;i<currentList.length;i++) {
				money = currentList[i].money;
				money = (money <= 1 ? 1 : money);
				list.push({"id" : currentList[i].id,
					"name" : currentList[i].name,
					"image" : currentList[i].image,
					"money" : money
				});
			} 
			list.splice(0, 0, {"id" : 0,
				"name" : '谢谢惠顾',
				"image" : $('#sorry-img').attr('src'),
				"money" : 0
			});
			initSurf();
		}
		function initSurf(){
			for(var i=0;i<list.length;i++) {
				if (list[i].money >0  ) {	//中奖后再根据价格抽取奖品
                    list[i].percent  = setting.pay_money*(share_mode?share_x:x)/(list.length-1)/list[i].money;
				} else {		//未中奖概率
					list[i].percent = (rate>=100 ? 0 : (100-rate))
				}
			}
			// 定义转盘
			if(wheelSurf) {
				wheelSurf.initList(list);
			} else {
				wheelSurf = $('#myCanvas').WheelSurf({
					list: list, // 奖品 列表，(必填)
					outerCircle: {
						color: '#df1e15' // 外圈颜色(可选)
					},
					innerCircle: {
						color: '#f4ad26' // 里圈颜色(可选)
					},
					dots: ['#fbf0a9', '#fbb936'], // 装饰点颜色(可选)
					disk: ['#FFF4D6', '#ffe8b5', '#fc9933', '#ffd57c', '#ffb933'] //中心奖盘的颜色，默认7彩(可选)
				});
			}
			// 初始化转盘
			wheelSurf.init();
		}

		function hiddenMessage(){
			$(".success").css("display","none");
			$(".fail").css("display","none");
			throttle = false;
		}
        
        function paymented(){
            checkPaymentedTimes = -1;
            throttle = true;
            $(".pageMask").show();
            winData = getGift(); // 正常情况下获奖信息应该由后台返回
            if(winData){
                wheelSurf.lottery(winData.id, function () {
                    showResult();
                    throttle = false;
                    $(".pageMask").hide();
                })
            }
            //抽奖次数+1
            $.get(apiHost + "/cache.app.plus?app_id=" + app_id + "&key=plugin.zhuanpan.times."+account.id+"&value=1");
            hideLoading();
        }
        let out_trade_no;
        let checkPaymentedTimes = 0;
		function start() {
            if(throttle){
                return;
            }
            if(!$("#Agreement").prop("checked")){
                alert("您必须同意《幸运抽奖活动使用协议》");
                return;
            }
            //初始化参数
            checkPaymentedTimes = 0;
            $(".paymentAction").hide();
            showLoading();
            //判断用户是否满足免单抽奖条件(并且分享模式不可用) start
            if(setting!=null&&!share_mode){
                let tradeCount = 0;
                let moneyCount = 0;
                let myTimes = 0;
                $.ajax({
                    async: false,
                    type: "GET",
                    dataType: "json",
                    url:apiHost + "/my.trade.count.paymented?app_id=" + app_id,
                    success:function(res){
                        tradeCount = res.result.count;
                    },
                    error:function(){
                        alert("读取有效订单数量统计信息异常");
                    }
                });
                $.ajax({
                    async: false,
                    type: "GET",
                    url:apiHost + "/cache.app.get?app_id=" + app_id+"&key=plugin.zhuanpan.times."+account.id,
                    success:function(res){
                        myTimes = Number(res);
                    }
                });
                $.ajax({
                    async: false,
                    type: "GET",
                    dataType: "json",
                    url:apiHost + "/my.trade.count.money?app_id=" + app_id,
                    success:function(res){
                        moneyCount = res.result.count;
                    },
                    error:function(){
                        alert("读取个人消费总额统计异常");
                    }
                });
                let availability_trade_amount = Math.floor(tradeCount/setting.trade_amount*setting.times);
                let availability_trade_money = Math.floor(moneyCount/setting.trade_money*setting.times);
                if(setting.relationship=="and"&&(availability_trade_amount<=myTimes||availability_trade_money<=myTimes)){
                    alert("您的抽奖配额次数不足。在本店完成"+setting.trade_amount+"笔订单交易，并且交易金额达到"+setting.trade_money+"元，可增加抽奖次数"+setting.times+"次");
                    hideLoading();
                    return;
                }else if(availability_trade_amount<=myTimes&&availability_trade_money<=myTimes){
                    alert("您的抽奖配额次数不足。在本店完成"+setting.trade_amount+"笔订单交易，或者交易金额达到"+setting.trade_money+"元，可增加抽奖次数"+setting.times+"次");
                    hideLoading();
                    return;
                }
            }
            //判断用户是否满足免单抽奖条件 end
            
			if(!throttle && !ispaying){
                let productids = new Array();
                let productidMoneys = new Array();
                currentList.forEach(function(pro){
                    productids.push(pro.id);
                    productidMoneys.push(pro.money);
                });
                out_trade_no = account.id+"_"+productidMoneys.join("_")+"_"+new Date().getTime();
                if(!share_mode){
                    if(account.score>=x*setting.pay_money){
                        $.get(apiHost+"/remote.call",{url:"https://service-p5l2zor3-1255950678.ap-shanghai.apigateway.myqcloud.com/release/score?product_id="+productids.join(",")+"&token="+token+"&contacts="+encodeURIComponent(contacts)+"&telephone="+telephone+"&charge_mode=salemoney&plugin_id=zhuanpan&lucky_mode=single&out_trade_no="+out_trade_no+"&app_id="+appId+"&account_id="+account.id+"&pay_score="+(x*setting.pay_money)},function(res){
                            if(res.error){
                                hideLoading(res.message);
                            }else{
                                account.score -= x*setting.pay_money;
                                updateMyScore();
                                luckyResult = res;
                                paymented();
                            }
                        }).error(function(err){
                            hideLoading(JSON.parse(err.responseText).message);
                        });
                    }else if(x==1&&account.score>0){
                        $.get(apiHost+"/remote.call",{url:"https://service-p5l2zor3-1255950678.ap-shanghai.apigateway.myqcloud.com/release/score?product_id="+productids.join(",")+"&token="+token+"&contacts="+encodeURIComponent(contacts)+"&telephone="+telephone+"&charge_mode=salemoney&plugin_id=zhuanpan&lucky_mode=single&out_trade_no="+out_trade_no+"&app_id="+appId+"&account_id="+account.id+"&pay_score="+account.score},function(res){
                            if(res.error){
                                hideLoading(res.message);
                            }else{
                                account.score = 0;
                                updateMyScore();
                                luckyResult = res;
                                paymented();
                            }
                        }).error(function(err){
                            hideLoading(JSON.parse(err.responseText).message);
                        });
                    }else{
                        function callpayment(){
                            let paymentedBack = false;
                            function _checkPayment(showMessage){
                                $.get(apiHost+"/cache.global.hget",{key:"zhuanpan.islucky",field:out_trade_no},function(res){
                                    if(res){
                                        paymentedBack = true;
                                        luckyResult = JSON.parse(res);
                                        paymented();
                                    }else{
                                        paymentedBack = false;
                                        if(showMessage){
                                            alert("未检测到付款记录，请稍后再试");
                                        }
                                    }
                                });
                            }
                            $.get(apiHost+"/payment",{money:x*setting.pay_money/100,body:"幸运抽奖",out_trade_no:out_trade_no,trade_type:"callback:https://service-p5l2zor3-1255950678.ap-shanghai.apigateway.myqcloud.com/release/lucky?product_id="+productids.join(",")+"&token="+token+"&contacts="+encodeURIComponent(contacts)+"&telephone="+telephone+"&charge_mode=salemoney&plugin_id=zhuanpan&lucky_mode=single",pay_type:"JSAPI"},function(payres){
                                let paymentCheckTimeout = 0;
                                let paymentCheckInterval = 0;
                                wxapi.call("requestPayment",payres,{success:function(){
                                    _checkPayment();
                                    paymentCheckInterval = window.setInterval(
                                        function(){
                                            if(paymentedBack){
                                                window.clearInterval(paymentCheckInterval);
                                                window.clearTimeout(paymentCheckTimeout);
                                            }else{
                                                _checkPayment();
                                            }
                                        }
                                    ,1000);
                                   
                                },fail:function(){
                                    window.clearTimeout(paymentCheckTimeout);
                                    hideLoading();
                                }});
                                paymentCheckTimeout = window.setTimeout(function(){
                                    window.clearInterval(paymentCheckInterval);
                                    $(".score_product").hide();
                                    $(".paymentAction").show();
                                    $(".restartCheck").click(function(){
                                        _checkPayment(true);
                                    });
                                },35000);
                                
                            }).error(function(err){
                                hideLoading(JSON.parse(err.responseText).message);
                            });
                        }
                        if(setting.score_product){

                            $.get(apiHost+"/product.get?product_id="+setting.score_product.id,null,function(s_product){
                                if(!s_product.result.activated){
                                    callpayment();
                                    return;
                                }

                                //获取商品积分信息
                                $.get(apiHost+"/remote.call?url="+encodeURIComponent("https://service-2wggf83t-1255950678.ap-shanghai.apigateway.myqcloud.com/release/get-product-score?app_id="+app_id+"&product_id="+s_product.result.id),null,function(config_score){
                                    if(config_score){//已配置积分则弹出购买积分商品提示
                                        $(".score_product_pic").html("<img src=\""+s_product.result.album[0]+"?imageView2/5/w/150/h/150\"/>");
                                        $(".score_product_title").html(s_product.result.name);
                                        $(".score_product_money").html("价格：￥"+s_product.result.salemoney+"元");
                                        let p_amount = 0;
                                        let p_score = account.score;
                                        while(p_score<x*setting.pay_money){
                                            p_score += config_score;
                                            p_amount++;
                                        }
                                        $(".score_product_amount").html("数量："+p_amount+"件");
                                        $(".score_product_give").html("赠送："+(p_amount*config_score)+"积分");
                                        $("#score_product_cancel").unbind("click");
                                        $("#score_product_ok").unbind("click");
                                        $("#score_product_cancel").click(function(){
                                            $(".score_product").hide();
                                        });
                                        $("#score_product_ok").click(function(){
                                            showLoading();
                                            //创建推荐商品订单
                                            $.ajax({
                                                url:apiHost+"/trade.create?contacts="+encodeURIComponent(contacts)+"&telephone="+telephone+"&discountId=&couponRecordId=&areaId=&address=&expressId=&takeBySelf=true&pluginId=zhuanpan&customerRemarks="+encodeURIComponent("幸运抽奖推荐商品"),
                                                type:"POST",
                                                data:JSON.stringify([{product:{id:setting.score_product.id},amount:p_amount}]),
                                                contentType:"application/json;charset=utf-8",
                                                dataType:"json",
                                                success:function(trade){
                                                    function _checkPayment(checktimes){
                                                        $.get(apiHost+"/trade.paymented.check?serial_number="+trade.serialNumber+"&times="+(checktimes?checktimes:1),null,function(checkResult){//同步检测订单知否支付成功，10次

                                                            if(checkResult.success){
                                                                account.score = p_score;
                                                                start();
                                                            }else{
                                                                alert(checkResult.message);
                                                            }
                                                        }).error(function(err){
                                                             hideLoading(JSON.parse(err.responseText).message);
                                                        }).always(function(){
                                                            $(".score_product").hide();
                                                        });
                                                    }
                                                    $.get(apiHost+"/trade.payment",{trade_id:trade.id,pay_type:"JSAPI"},function(payres){
                                                        let paymentCheckTimeout = 0;
                                                        wxapi.call("requestPayment",payres,{success:function(){
                                                            window.clearTimeout(paymentCheckTimeout);
                                                           _checkPayment(30);
                                                        },fail:function(){
                                                            window.clearTimeout(paymentCheckTimeout);
                                                            hideLoading();
                                                        }});
                                                        paymentCheckTimeout = window.setTimeout(function(){
                                                            $(".score_product").hide();
                                                            $(".paymentAction").show();
                                                            $(".restartCheck").click(function(){
                                                                _checkPayment(1);
                                                            });
                                                        },35000);
                                                    }).error(function(err){
                                                        hideLoading(JSON.parse(err.responseText).message);
                                                    });
                                                    
                                                },
                                                error:function(err){
                                                    hideLoading(JSON.parse(err.responseText).message);
                                                }
                                            });
                                        });
                                        $(".score_product").show();
                                        hideLoading();
                                    }else{//未配置积分则直接付款
                                        callpayment();
                                    }
                                }).error(function(err){
                                    hideLoading(JSON.parse(err.responseText).message);
                                });
                            }).error(function(err){
                                hideLoading(JSON.parse(err.responseText).message);
                            });
                        }else{
                            callpayment();
                        }
                    }
                    
                }else{
                    //广播分享抽奖开始事件通知
                    $.get(apiHost+"/remote.call",{url:"https://service-p5l2zor3-1255950678.ap-shanghai.apigateway.myqcloud.com/release/free?product_id="+productids.join(",")+"&token="+token+"&contacts="+encodeURIComponent(contacts)+"&telephone="+telephone+"&charge_mode=salemoney&plugin_id=zhuanpan&lucky_mode=single&out_trade_no="+out_trade_no+"&app_id="+appId+"&account_id="+account.id},function(res){
                        luckyResult = res;
                        paymented();
                        window.dispatchEvent(new CustomEvent("share-started",{detail:true}));
                    }).error(function(err){
                        hideLoading(JSON.parse(err.responseText).message);
                    });
                }
			}
		}

        //轮训检测订单支付情况
        function checkPaymented(wait){
            if(checkPaymentedTimes==-1){
               return;
            }
            if(checkPaymentedTimes>30){
                $(".paymentAction").show();
            }
            checkPaymentedTimes++;
            if(checkPaymentedTimes==0){
                showLoading();
            }
            setTimeout(function(){
                $.get(apiHost+"/cache.global.hget",{key:"zhuanpan.islucky",field:out_trade_no},function(res){
                    if(res){
                        luckyResult = JSON.parse(res);
                        paymented();
                    }else{
                        checkPaymented(1000);
                    }
                });
            },wait?wait:0);
        }
        //手动确认付款
        $(".continueToWait").click(function(){
            /*$.get(apiHost+"/cache.global.hget",{key:"zhuanpan.islucky",field:out_trade_no},function(res){
                if(res){
                    luckyResult = JSON.parse(res);
                    paymented();
                }else{
                    alert("未检测到您的付款记录，如有疑问请凭微信支付结果详情截图与管理员联系确认是否中奖。");
                    $(".cancelWait").show();
                }
            })*/
            window.location.href = "my-record.html";
        });
        //取消付款
        $(".cancelWait").click(function(){
            checkPaymentedTimes = -1;
            hideLoading();
        });
		// 计算获奖概率
		function getGift(){
            //由服务器返回指定的中奖商品ID start
            if(luckyResult.lucky==true){
               for(var i = 0 ,l = list.length;i<l;i++){
                    if(luckyResult.lucky_products[0].id==list[i].id){
                        return list[i];
                    }
                }
            }
            return list[0];
		}
        //要求用户输入手机号姓名
        function showContacts(){
            $("#contacts").show();
        }
        $("#contactsBtn").click(function(){
            contacts = $("#contacts").val();
            telephone = $("#telephone").val();
            $.ajax({
                url: apiHost + "/cache.app.set?app_id=" + appId + "&key=zhuanpan.contacts."+account.id,
                type: "POST",
                contentType: "text/plain; charset=utf-8",
                data: JSON.stringify({contacts:contacts,telephone:telephone}),
                success: function(res) {
                    $(".contacts").hide();
                },
                error: function(jqXHR) {
                    alert(jqXHR.responseJSON.message);
                }
            });  
        });
        if(!(contacts&&telephone)){
            showContacts();
        }
		//显示结果
		function showResult(){
			if( winData && winData.id != 0 ) {
                let pnames = new Array();
                luckyResult.lucky_products.forEach(function(p){
                    pnames.push(p.name);
                });
                $("#product").html(pnames.join("、"));
                $(".success").css("display","flex");
                $("#ladingCode").html("");
                $("#ladingCodeMessage").html("正在获取提货码，请稍等...");
                
                    let scene = JSON.stringify({action:"takeGoods",tradeId:luckyResult.trade_id,appId:appId});
                   let imgSrc = apiHost+"/wx.app.qrcode.appcenter.launch?&scene="+encodeURIComponent(scene)+"&width=550";
                   let flushLadingCode = $("<a>刷新</a>");

                   let img = $("<img src=\""+imgSrc+"\"/>");
                   flushLadingCode.click(function(){
                       img.prop("src",imgSrc+"&r="+new Date().getTime());
                   });
                   flushLadingCode.appendTo($("#ladingCodeMessage"));
                   img.load(function(){
                       $("#ladingCodeMessage").html("将此提货码发送给客服兑奖<br/>");
                       let openTrade = $("<a>提货码已存放到中奖纪录中(点击查看)</a>");
                       openTrade.click(function(){
                            window.location.href = "my-record.html?app_id="+appId;
                       });
                       $("#ladingCodeMessage").append(openTrade);
                       $("#ladingCodeMessage").append($("<p>中奖商品"+luckyResult.lucky_products.length+"件，总计："+luckyResult.lucky_money+"元</p>"));
                   });
                   img.click(function(){
                       showLoading();
                       $.ajax({
                            url:apiHost+"/wx.app.call?name=previewImage&asyn=true",
                            type:"POST",
                            data:JSON.stringify({current:imgSrc,urls:[imgSrc]})
                        }).always(function(){
                           hideLoading();
                       });
                   });
                   img.appendTo($("#ladingCode"));
                
                
			} else {
                
                $(".failMessage").html("");
                $(".failMessage").append($("<p>您此次微信支付交易尾号为："+luckyResult.lucky_number+"</p>"));
                $(".failMessage").append($("<p>参与抽奖商品件数为："+luckyResult.events.length+"件</p>"));
                $(".failMessage").append($("<p>此次倍率为："+(luckyResult.total_fee)+"(平均每件商品倍率为"+(luckyResult.avg_fee)+")</p>"));
                $(".failMessage").append($("<p>微信支付交易尾号除以每件商品价格(分)所得余数在0-"+(luckyResult.avg_fee-1)+"之间即中奖</p>"));
                $(".failMessage").append($("<p>抽奖结果：</p>"));
                let detail = $("<p class=\"detail\"></p>").appendTo($(".failMessage"));
                luckyResult.events.forEach(function(event){
                    detail.append($("<span><strong>"+event.product_name+"</strong>价格"+(event.money/100)+"元("+event.money+"分)，"+luckyResult.lucky_number+"除以"+event.money+"所得余数"+event.lucky_number_mod+"不在0-"+(luckyResult.avg_fee-1)+"之间</span>"));
                });
                $(".failMessage").append($("<p><strong>规则详情请见底部《幸运抽奖活动使用协议》</strong></p>"));
				$(".fail").css("display","flex");
			}
		};
        
		//换一批
		$("#reroll").click(function(){
			initList();
			hiddenMessage();
		});
		
		//倍数
		$(".rate").click(function(){
			if(!throttle && !ispaying){
				document.querySelectorAll(".rate").forEach(function(item){
					$(item).removeClass("selected")
				});
				$(this).addClass("selected");
				x = Number($(this).attr("x"));
				initSurf();
			}
		});
		$("#success_ok").click(function(e){
             hiddenMessage();
        });
		$("#viewTrade").click(function(e){
            wx.miniProgram.reLaunch({url:"/pages/index/index?scene="+encodeURIComponent(JSON.stringify({action:"openItem",productId:winData.id}))});
		});
		$("#cancel").click(function(e){
			hiddenMessage();
		});
		$("#restart").click(function(e){
			hiddenMessage();
			start();
		});
		// 抽奖
		$("#start").on('click', function () {
			start();
		});
        //生成二维码
        $(".qrcode").click(function(){
            showLoading();
            var conf = {uid:account.id,url:window.location.href,sid:"zhuanpan."+account.id,trigger:"https://service-p5l2zor3-1255950678.ap-shanghai.apigateway.myqcloud.com/release/share-event?plugin_id=zhuanpan"};
            let imgURL = apiHost+'/wx.app.qrcode.shop.launch?app_id='+appId+'&scene=share:'+encodeURIComponent(JSON.stringify(conf))+'&width=100';
            $.ajax({
                url:apiHost+"/image.merge",
                type:"POST",
                contentType:"application/x-www-form-urlencoded",
                data:{back:"https://cdn.image.b2wx.com/plugin/icons/zhuanpan/zj.png",front:imgURL,x:10,y:10},
                success:function(res){
                   $.ajax({
                        url:apiHost+"/wx.app.call?name=previewImage&asyn=true",
                        type:"POST",
                        data:JSON.stringify({current:res,urls:[res]})
                    }).always(function(){
                       hideLoading();
                   });
                }
            }).error(function(){
                hideLoading();
            });
        });
        $(".shop_home").click(function(){
            wx.miniProgram.reLaunch({url:"/pages/index/index"});
        });
        $(".shop_record").click(function(){
            window.location.href = "my-record.html?app_id="+appId;
        });
        $(".my-score").click(function(){
            $(this).addClass("update");
            updateAccount();
            updateMyScore();
        });
        function updateMyScore(){
            $(".my-score").html("可用积分："+account.score);
        }
        $(function(){
            updateMyScore();
        });
		init();
	</script>
    <script type="application/javascript">
        /*分享抽奖*/
        $(function(){
            if(setting.share_open){
                if(GetQueryString("share_answer_to")){
                    $.get(apiHost+"/account.get?app_id="+appId+"&account_id="+GetQueryString("share_answer_to"),null,function(rs){
                        alert("由于你的支持，"+rs.result.nick_name+"大大增加了中奖机会，"+(rs.result.gender==2?"她":"他")+"已知晓，表示对你感谢:)，你是否也有兴趣玩一把呢？");
                    });
                }
                $.ajax({
                    url:apiHost+"/image.merge",
                    type:"POST",
                    contentType:"application/x-www-form-urlencoded",
                    data:{back:"https://cdn.image.b2wx.com/plugin/icons/zhuanpan/zhongjiang.png",front:account.avatar_url,x:10,y:10},
                    success:function(res){
                        wx.miniProgram.postMessage({data:{pageURL:window.location.href,share:{title:account.nick_name+"：“寻求帮忙，在线等！”",imageUrl:res,sid:"zhuanpan."+account.id,url:window.location.href,trigger:"https://service-p5l2zor3-1255950678.ap-shanghai.apigateway.myqcloud.com/release/share-event?plugin_id=zhuanpan"}},});
                    }
                });
                
                let share_amount_point = setting.share_amount;
                $(".share_amount_point").html(share_amount_point);
                window.addEventListener("share-started",function(){
                    share_mode = false;
                    share_x = 0;
                    $(".share_answer_count").html("0人已响应");
                    $(".share_rate_mul_show").html("0倍");
                    $(".share_rate_mul").css("width","0%");
                    $(".share_mode").css("display","none");
                    initSurf();
                });
                $(".share").show();
                if(!window.localStorage.getItem("share_tip")){
                    $(".share_tip").css("display","flex");
                }
                $(".share_tip_close").click(function(){
                    $(".share_tip").hide();
                    window.localStorage.setItem("share_tip","readed");
                });
                $(".share_history").click(function(){
                    $(this).toggle();
                });
                $(".share_message").click(function(){
                    $(".share_history").toggle(function(){
                        $(".share_history").html("");
                        $.get(apiHost+"/remote.call",{url:"https://service-p5l2zor3-1255950678.ap-shanghai.apigateway.myqcloud.com/release/share-answer-history?start=0&end=99&sid=zhuanpan."+account.id+"&plugin_id=zhuanpan"},function(res){
                            res.forEach(function(history){
                                $(".share_history").append($("<p><span><strong>"+history.from.nickName+"</strong>响应了你的分享</span><span>"+util._date(history.eventTime)+"</span></p>"));
                            });
                        });
                    });
                });
                function answerEvent(share_answer_available){
                    share_answer_available = share_answer_available?share_answer_available:0;
                    $(".share_answer_count").html(share_answer_available+"人已响应");
                    if(share_answer_available>=share_amount_point){
                        x = 1;
                        if(setting.share_multiple_rate){
                            share_x = Number((share_answer_available/share_amount_point).toFixed("1"))-1;
                            $(".share_rate_mul").css("width",(((share_x+1)/5)*100)+"%");
                            $(".share_rate_mul_show").html((share_x+1)+"倍");
                            $(".share_mode").html("免费抽奖("+(share_x+1)+"倍概率)");
                        }
                        share_mode = true;
                        $(".share_mode").css("display","flex");
                        initSurf();
                    }
                }
                $.get(apiHost+"/remote.call",{url:"https://service-p5l2zor3-1255950678.ap-shanghai.apigateway.myqcloud.com/release/available?account_id="+account.id+"&plugin_id=zhuanpan"},function(res){
                    answerEvent(Number(res));
                });
                let broadcastWait = 0;
                var heartbeat = 0;
                var ws = null;
                function testWebsocket(){
                    if(ws!=null&&ws.readyState!=1){
                        startws();
                    }
                }
                document.addEventListener("click",testWebsocket);
                document.addEventListener("touch",testWebsocket);
                document.addEventListener("touchmove",testWebsocket);
                function startws(){
                    ws = new WebSocket("wss://"+window.location.hostname+"/websocket/p2p?zhuanpan."+account.id);
                    heartbeat = 0;
                    ws.addEventListener("open",function(res){
                        heartbeat = window.setInterval(function() {
                            ws.send("heartbeat");
                        }, 3000);
                    });
                    ws.addEventListener("message",function(info){
                        if(info.data=="heartbeat"){
                            return;
                        }
                        let message = JSON.parse(info.data);
                        if(message.type=="broadcast"){
                            window.setTimeout(function(){
                                let broadcast = $("<div>"+message.message+"</div>").addClass("broadcast").appendTo($(document.body));
                                broadcast.css("left",$(document.body).width()+"px").show().animate({left:(broadcast.width()*-1)+"px"},10000,function(){
                                    broadcastWait -= 10000;
                                    broadcast.remove();
                                });
                            },broadcastWait);
                            broadcastWait +=10000;
                            return;
                        }
                        
                        $(".share_message").html(message.from.nickName+"已响应您的分享");
                        answerEvent(message.available);
                    });
                    ws.addEventListener("close",function(){
                        window.clearInterval(heartbeat);
//                        alert("消息通知服务已经断开，确认后重新尝试连接");
                        //window.setTimeout(startws,1500);
                    });
                }
                startws();
            }
        });
    </script>
    
</body>
</html>